/* eslint-disable no-async-promise-executor */
const model = require("../models/model")
const { getFile } = require('../models/getfile')
exports.modifySku = async(ctx) => {
  const { id, k, largeImageMode } = ctx.request.body
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
  function edit() {
    return new Promise(async(resolve) => {
      let data = {
        k: k,
        largeImageMode: largeImageMode
      }
      for (const prop in data) {
        if (data[prop] == undefined || data[prop] == null) {
          delete data[prop]
        }
      }
      if (data.largeImageMode !== undefined) {
        data.largeImageMode = data.largeImageMode ? 1 : 0
      }
      if (!data.k && !data.largeImageMode) {
        resolve(-1)
        return
      }
      const res = await MyGoodsListSku.update(data, {
        where: {
          id: id
        }
      })
      if (res) {
        resolve(res)
      }
    })
  }

  function add() {
    return new Promise(async(resolve) => {
      let data = {
        k: k,
        largeImageMode: largeImageMode
      }
      for (const prop in data) {
        if (data[prop] == undefined || data[prop] == null) {
          delete data[prop]
        }
      }
      if (data.largeImageMode !== undefined) {
        data.largeImageMode = data.largeImageMode ? 1 : 0
      }
      if (!data.k && !data.largeImageMode) {
        resolve(-1)
        return
      }
      const res = await MyGoodsListSku.create(data) // 先创建该记录
      if (res) {
        const res_all = await MyGoodsListSku.update( // 再以该id更新作为商品s标识
          {
            k_s: `s${res.id}`
          },
          {
            where: {
              id: res.id
            }
          }
        )
        if (res_all) {
          const { sequelize } = require('../config/db.js')
          // 新增了sku大类 对应的list表也要增加相应的字段
          sequelize.query(`alter table goodsdetails_list add s${res.id} int(11) default null`, { raw: true }).then(res => {
            if (res) resolve(res_all)
          })
        }
      }
    })
  }
  let res
  if (id) {
    res = await edit()
  } else {
    res = await add()
  }
  if (res !== -1) {
    ctx.success()
  } else {
    ctx.fail('参数错误')
  }
}

exports.getSkuList = async (ctx) => {
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
  let { page, size } = ctx.request.query
  page = parseInt(page)
  size = parseInt(size)
  if (!page || !size) {
    ctx.fail('参数错误')
    return
  }
  const res = await MyGoodsListSku.findAndCountAll({
    order: [
      ['updateTime', 'DESC'],
    ],
    offset: (page-1) * size,
    limit: size
  })
  if (res) {
    if (res.rows !== undefined && res.rows.length > 0) {
      res.rows.forEach(item => {
        if (item.largeImageMode !== undefined) {
          item.largeImageMode = item.largeImageMode == 0 ? false : true
        }
      })
    }
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  } else {
    ctx.fail()
  }
}
exports.deleteSku = async(ctx) => {
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
  const MyGoodsList = model.goodsdetailsList.MyGoodsList
  const { id } = ctx.request.query
  if (!id) {
    ctx.fail('参数错误')
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const find_all = await MyGoodsList.findAll({})
      if (find_all.length > 0) {
        let flag = 0
        for (let i = 0; i < find_all.length; i++) {
          if (find_all[i][`s${id}`] && find_all[i][`s${id}`] !== null) {
            flag++
            break
          }
        }
        if (flag === 0) {
          const res = await MyGoodsListSku.destroy({
            where: { id: id }
          })
          if (res) {
            const { sequelize } = require('../config/db.js')
            // 删除了sku大类 对应的list表也要删除相应的字段
            const delete_col = await sequelize.query(`alter table goodsdetails_list drop column s${id}`)
            if (delete_col) {
              resolve('success')
            } else {
              resolve('删除失败')
            }
          } else {
            resolve('没有该类别')
          }
        } else {
          resolve('该规格下有类目列表正在使用')
        }
      } else {
        resolve('没有该类别')
      }
    })
  }
  const res = await allFn()
  if (res === 'success') {
    ctx.success('', '删除成功')
  } else {
    ctx.fail(res)
  }
}


// 获取该商品的所有规格列表（根据商品id查询）
exports.getMyGoodsSku = async(ctx) => {
  const MyGoods = model.goodsdetails.MyGoods //获取模型
  const MyGoodsListType = model.goodsdetailsType.MyGoodsListType
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
  const { goodsId } = ctx.request.query
  if (!goodsId) {
    ctx.fail('参数错误')
    return
  }
  function skuPromise(skus) {
    return new Promise(async(resolve) => {
      const skuList = skus.split(',').filter(item => item !== '')
      if (skuList.length > 0) {
        //  先查询 规格类目
        const skuListPromise = skuList.map(it => MyGoodsListSku.findOne({ where: { k_s: it } }))
        const skuListPromiseAll = await Promise.all(skuListPromise)
        console.log(skuListPromiseAll, '主规格')
        if (skuListPromiseAll.length > 0) {
          // 再查询 规格类目下的具体子项 规格值
          const TypePromise = skuListPromiseAll.map(it => MyGoodsListType.findAll({ where: { skuId: it.id, parentId: goodsId } }))
          const TypePromiseAll = await Promise.all(TypePromise)
          console.log(TypePromiseAll, '副规个')
          if (TypePromiseAll.length > 0) {
            let vData = []
            TypePromiseAll.forEach(item => { // Promise.all生成了多个数组 进行拆解（把所有对象集合到一个数组里）
              if (Array.isArray(item)) { // 如果子集为数组继续循环
                item.forEach(it => {
                  if (Array.isArray(it)) {
                    it.forEach(v => {
                      vData.push(v) // 最多2级
                    })
                  } else {
                    vData.push(it)
                  }
                })
              } else {
                vData.push(item)
              }
            })
            const imgUrl = new Promise(async(resolve) => { // 获取规格类目图片，只有第一个规格类目可以定义图片
              let flag = 0
              if (vData.length > 0) {
                for (let i = 0; i < vData.length; i++) {
                  getFile(vData[i].imgUrl).then(res => {
                    flag++
                    vData[i].imgUrl = res
                    if (flag === vData.length) {
                      resolve('success')
                    }
                  })
                }
              } else {
                resolve('success')
              }
            })
            const previewImgUrl = new Promise(async(resolve) => { // 获取用于预览显示的规格类目图片
              let flag = 0
              if (vData.length > 0) {
                for (let i = 0; i < vData.length; i++) {
                  getFile(vData[i].previewImgUrl).then(res => {
                    flag++
                    vData[i].previewImgUrl = res
                    if (flag === vData.length) {
                      resolve('success')
                    }
                  })
                }
              } else {
                resolve('success')
              }
            })
            // 执行全部文件地址异步后再返回
            let fileAll = await Promise.all([imgUrl, previewImgUrl])
            if (fileAll) { // 获取图片地址后再返回
              // 合并数据
              skuListPromiseAll.forEach(item => {
                item.largeImageMode = item.largeImageMode != 0
                item['v'] = []
                vData.forEach(v => {
                  if (item.id == v.skuId) {
                    item['v'].push(v)
                  }
                })
              })
              resolve(skuListPromiseAll)
            }
          } else {
            resolve([])
          }
        } else {
          resolve([])
        }
      } else {
        resolve([])
      }
    })
  }

  function allFn() {
    return new Promise(async(resolve) => {
      const goods_res = await MyGoods.findOne({
        where: {
          id: goodsId
        }
      })
      if (goods_res) {
        const res = await skuPromise(goods_res.sku || '')
        resolve(res)
      } else {
        resolve()
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success(res)
  } else {
    ctx.fail('查询失败')
  }
}

